//
//  NSData+Expand.m
//  KEREN
//
//  Created by chenliang on 2023/8/9.
//

#import "NSData+Expand.h"

@implementation NSData (Expand)

-(int)ToInt{
    Byte *b = [self bytes];
    int s = (int)((b[3] & 0xFF)
            | ((b[2] & 0xFF) << 8)
            | ((b[1] & 0xFF) << 16)
            | ((b[0] & 0xFF) << 24));
    return s;
}

-(short)toShort{
    Byte *b = [self bytes];
    short s = (short)((b[1] & 0xFF)
            | ((b[0] & 0xFF) << 8));
    return s;
}

-(short)ToByteShort{
    Byte *b = [self bytes];
    int s = (int)(b[0] & 0xFF);
    return s;
}


-(NSString *)toHexString{
    
    if (!self || [self length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[self length]];
    [self enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}

-(NSData *)aes128CBC:(NSString *)key iv:(NSString *)iv mode:(CCOperation)operation{
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = self.length;
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void * buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    NSString * initIv = iv;
    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [initIv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    //Byte byte[16] = @{@x31}
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCKeySizeAES128,
                                          ivPtr,
                                          self.bytes,
                                          16,
                                          buffer,
                                          bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *result = [NSData dataWithBytes:buffer length:numBytesDecrypted];
        return result;
    }
    free(buffer);
    return nil;
}
@end
